package com.neha.demo;



import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * @author  
 * 
 */
public class Call_Receiver extends BroadcastReceiver {

	public static final long DAY_IN_MILISECONDS = 0;
	public static final String TAG = "Call_Receiver";
	private Context ctx;
	public long duration;
	public boolean wasRinging;
	private boolean FLAG_DISCONNECTED = false;



	@Override
	public void onReceive(final Context context, final Intent intent) {


		ctx = context;
		IncomingCallListener phoneListener = new IncomingCallListener();
		TelephonyManager telephony = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (intent.getAction()
				.equals("android.intent.action.NEW_OUTGOING_CALL")) {

			Log.i("", " :::::::::::: inside onReceive if &&&&&&  :::::::::::::");

			telephony.listen(phoneListener,
					PhoneStateListener.LISTEN_CALL_STATE);
			AppInfo.DIAL_ATTEMPTS --;

			AppInfo.MESSAGE_COUNTER++;
			Toast.makeText(context,"Dial attempts"+AppInfo.DIAL_ATTEMPTS,  Toast.LENGTH_SHORT).show();
			if (AppInfo.DIAL_ATTEMPTS == 0) {
				abortBroadcast();

				Toast.makeText(context,"is aborted",  Toast.LENGTH_SHORT).show();
			}


		}
	}

	class IncomingCallListener extends PhoneStateListener {

		public boolean isOffHook;

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				Log.i(TAG, "  ************  &&&&&&&&&& RINGING  ********"+incomingNumber);

				wasRinging = true;
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:

				Log.i(TAG,
						"  ***********  &&&&&&&&&&&&& OFFHOOK &&&&&&&&&& ********");
				isOffHook = true;
				setSpeaker();

				ContentResolver contentResolver = ctx.getContentResolver();
				CallLogObserver mObserver = new CallLogObserver(new Handler(),
						ctx);
				contentResolver.registerContentObserver(
						Uri.parse("content://call_log/calls"), true, mObserver);

				if (!wasRinging) {
					// Start your new activity
					Log.i(TAG, "  ***********  if  ********");
					setOffSpeaker();
				} else {
					// Cancel your old activity
					Log.i(TAG, "  ***********  else  ********");
				}

				// this should be the last piece of code before the break
				wasRinging = true;



				break;

			case TelephonyManager.CALL_STATE_IDLE:

				Log.i(TAG, "  ::::::::::: IDLE  :::::::::");
				// this should be the last piece of code before the break
				// Log.i("", "  ***********  OFFHOOK  ********");
				Log.i(TAG, "  ::::::::::: isOffHook  :::::::::" + isOffHook);

				Log.i(TAG, "  ::::::::::^^^^^^^^: duration  :::::::::"
						+ duration);


				AudioManager audioManager = (AudioManager) ctx
						.getSystemService(Context.AUDIO_SERVICE);
				//audioManager.setMode(AudioManager.MODE_IN_CALL); 
				audioManager.setSpeakerphoneOn(false);



				wasRinging = true;


				break;
			}
		}

		private void setOffSpeaker() {
			AudioManager audioManager = (AudioManager) ctx
					.getSystemService(Context.AUDIO_SERVICE);
			//audioManager.setMode(AudioManager.MODE_IN_CALL); 
			audioManager.setSpeakerphoneOn(false);

		}

		private void setSpeaker() {
			AudioManager audioManager = (AudioManager) ctx
					.getSystemService(Context.AUDIO_SERVICE);
			audioManager.setMode(AudioManager.MODE_NORMAL);
			audioManager.setSpeakerphoneOn(true);
			Toast.makeText(ctx, "Mode "+audioManager.getMode(), Toast.LENGTH_SHORT).show();
			Log.d("Call_Receiver", "Mode "+audioManager.getMode());

			//audioManager.setSpeakerphoneOn(true);




		}

		public class CallLogObserver extends ContentObserver {
			private Context context;


			public CallLogObserver(Handler handler, Context context) {
				super(handler);
				this.context = context;
			}

			@Override
			public void onChange(boolean selfChange) {
				super.onChange(selfChange);
				Log.i(TAG, "CallLogs Onhange()");
				try {
					Cursor c = context.getContentResolver().query(
							CallLog.Calls.CONTENT_URI, null, null, null,
							CallLog.Calls.DATE + " DESC");
					if (c != null) {
						if (c.moveToFirst()) {
							int type = Integer.parseInt(c.getString(c
									.getColumnIndex(CallLog.Calls.TYPE)));
							/*
							 * increase call counter for outgoing call only
							 */
							if (type == 2) {
								String number = c.getString(c
										.getColumnIndex(CallLog.Calls.NUMBER));

								duration = c.getLong(c
										.getColumnIndex(CallLog.Calls.DURATION));

								Log.i(TAG, "numer = " + number + " type = " + type
										+ " duration = " + duration);

							}

							if (duration == 0 && wasRinging) {
								if (AppInfo.DIAL_ATTEMPTS>0) {
									/*Toast.makeText(ctx,
																"Your call is disconnected by receiver",
																Toast.LENGTH_LONG).show();*/
									if (AppInfo.DIAL_ATTEMPTS % 2 != 0) {
										dialFirstNumber();
										AppInfo.MESSAGE_COUNTER = 1;

									} else {
										dialSecondNumber();
										AppInfo.MESSAGE_COUNTER = 2;
									}
								}else{
									// code for sending message
									//ctx.unregisterReceiver(new Call_Receiver());
									Toast.makeText(context,"no more dial attempts",  Toast.LENGTH_SHORT).show();
									if (AppInfo.COUNT != 1) {
										if (AppInfo.MESSAGE_COUNTER == 1) {
											sendMessage("5556");
											AppInfo.COUNT = 1;
										}else {
											sendMessage("5558");
											AppInfo.COUNT = 1;
										}

									}

								}




							} else {

								// code for sending text message
							}

						}
						c.close();
					} else
						Log.e(TAG, "Call Logs Cursor is Empty");
				} catch (Exception e) {

					Log.e("", "Error on onChange : " + e.toString());
				}
			}

			private void sendMessage(String number) {
				SmsManager sm = SmsManager.getDefault();
				String msg = "Message from Demo auto SmsManager";
				sm.sendTextMessage(number, null, msg, null, null);

			}

			private void dialFirstNumber() {
				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {

					public void run() {
						String mobileNo = "5556";
						String uri = "tel:" + mobileNo.trim();
						Intent intent = new Intent(Intent.ACTION_CALL);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setData(Uri.parse(uri));
						ctx.startActivity(intent);

					}
				}, Toast.LENGTH_LONG);








			}
			private void dialSecondNumber() {

				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {

					public void run() {
						String mobileNo = "5558";
						String uri = "tel:" + mobileNo.trim();
						Intent intent = new Intent(Intent.ACTION_CALL);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setData(Uri.parse(uri));
						ctx.startActivity(intent);

					}
				}, Toast.LENGTH_LONG);

				/*String mobileNo = "5558";
				String uri = "tel:" + mobileNo.trim();
				Intent intent = new Intent(Intent.ACTION_CALL);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setData(Uri.parse(uri));
				ctx.startActivity(intent);*/






			}


		}



	}
}